#region license
# This file is part of Grawlix.
# 
# Grawlix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
# 
# Grawlix is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public
# License along with Grawlix.  If not, see
# <http://www.gnu.org/licenses/>.
#endregion

"""Common <ITypedResolver[of T]> implementations."""

namespace Grawlix.Services.Resources
import Grawlix.Services
import System

abstract transient class TypedResolverBase[of T(class)](
	ServiceBase,
	ITypedResolver[of T]):
"""A service that resolves URIs into typed objects."""
	
	protected def constructor(
		streamResolver as IStreamResolver,
		embeddedResolver as IEmbeddedResolver,
		uriResolver as IUriResolver):
	"""
	Initializes a new typed resolver.
	Param streamResolver: The URI-to-stream translator.
	Param embeddedResolver: The URI-to-embedded resource translator.
	Param uriResolver: The URI translator.
	"""
		_streamResolver = streamResolver
		_embeddedResolver = embeddedResolver
		_uriResolver = uriResolver
	
	def Load([required] uri as Uri, allowLocal as bool) as T:
	"""
	Loads a typed object by its URI.
	Param uri: The URI which identifies the typed object.
	Param allowLocal: Whether to allow local URI schemes,
		such as file:// and internal://.
	Returns: The typed object.
	Raises IOException: A generic I/O error occurred.
	Raises FileNotFoundException:
		The URI could not be resolved or the object is the wrong type.
	Remarks: Note that this is a blocking operation which should only be
		called asynchronously to avoid making the game hang. Reading from
		the stream is also a blocking operation.
	"""
		typed = TryLoad(uri, allowLocal)
		return typed unless typed is null
		raise IO.FileNotFoundException(
			"A request was made to resolve a universal resource identifier " +
			"(${uri}) to a ${T}, but the resource could not be found. " +
			"The resource requested was not necessarily a critical " +
			"component, but it will not be accessible.")
	
	def TryLoad([required] uri as Uri, allowLocal as bool) as T:
	"""
	Loads a typed object by its URI.
	Param uri: The URI which identifies the typed object.
	Param allowLocal: Whether to allow local URI schemes,
		such as file:// and internal://.
	Returns: The typed object found, or null if not found or invalid.
	Raises IOException: A generic I/O error occurred.
	Remarks: Note that this is a blocking operation which should only be
		called asynchronously to avoid making the game hang. Reading from
		the stream is also a blocking operation.
	"""
		resolved = _uriResolver.TryResolve(uri, allowLocal)
		return null if resolved is null
		return LoadResolved(resolved)
	
	protected virtual def LoadResolved([required] uri as Uri) as T:
	"""
	Loads a typed object from a resolved URI.
	Param uri: The resolved URI to load from.
	Returns: The represented object, or null.
	Remarks: The default implementation handles
		File and Internal schemes.
	"""
		if uri.Scheme == Uri.UriSchemeFile:
			stream = _streamResolver.TryOpen(uri, true)
			return null if stream is null
			return LoadFromStream(stream)
		if uri.Scheme == DefaultUriResolver.InternalScheme:
			embeddedResource = _embeddedResolver.TryLoad(uri, true)
			return null if embeddedResource is null
			return LoadFromEmbeddedResource(embeddedResource)
		return null
	
	protected virtual def LoadFromStream([required] stream as IO.Stream) as T:
	"""
	Loads a specified object from stream.
	Param stream: The stream to load from.
	Returns: The represented object, or null.
	"""
		return null
	
	protected virtual def LoadFromEmbeddedResource(
		[required] embeddedResource):
	"""
	Loads from an embedded resource.
	Param embeddedResource: The untyped resource to load.
	Returns: The loaded object, or null.
	Remarks: The default implementation attempts a cast.
	"""
		typedResource = embeddedResource as T
		return typedResource unless typedResource is null
		byteArray = embeddedResource as (byte)
		unless byteArray is null:
			using stream = IO.MemoryStream(byteArray, false):
			# TODO: Probably will throw. Exception catching here?
				return LoadFromStream(stream)
		return null
	
	override def ToString():
	"""
	Get a string representation for this object.
	Returns: A string representation for this object.
	"""
		return "TypedResolver<${T}>"
	
	[getter(StreamResolver, Protected: true)]
	private _streamResolver as IStreamResolver
	"""The URI-to-stream translation service."""
	
	[getter(EmbeddedResolver, Protected: true)]
	private _embeddedResolver as IEmbeddedResolver
	"""The URI-to-embedded resource translation service."""
	
	[getter(UriResolver, Protected: true)]
	private _uriResolver as IUriResolver
	"""The URI translation service."""
